package cn.kgc.springmvc.controller;

import cn.kgc.springmvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/10/18
 */
@Controller
@RequestMapping("user")
public class UserController {


    // 基本类型参数的传递  请求路径中必须传参否则报错  添加注解解决参数报错问题  @RequestParam 设置默认值
    @RequestMapping("p1")
    public  String  param1(@RequestParam(defaultValue = "15") int id,@RequestParam(defaultValue = "30") int age){

        System.out.println("id="+id);
        System.out.println("age="+age);

        return "index";
    }

    // 使用包装类型接收参数   解决使用基本类型接收参数报错问题  /user/p2?id=15&age=20  required 默认是true  参数必须传递
    @RequestMapping("p2")
    public  String  param2(@RequestParam(name = "id") Integer id,@RequestParam(name = "ag",required = false) Integer age){

        System.out.println("id="+id);
        System.out.println("age="+age);

        return "index";
    }

    //使用自定义类型  User  user  保证使用路径传参时 参数的key要保持和自定义类型对象中的属性名一致  set方法
    @RequestMapping("p3")
    public  String  param3(User user){

        System.out.println(user);

        return "index";
    }


    //数组类型参数的接收
    @RequestMapping("p4")
    public  String  param4(Integer[] ids){
        for (Integer id : ids) {
            System.out.println("id = " + id);
        }
        return "index";
    }

    // ma集合接收参数    id = 10  age = 20
    @RequestMapping("p5")
    public  String  param5(@RequestParam  Map<String,Object> map){
        System.out.println("map = " + map);
        return "index";
    }

    //接收 json格式的数据   {name:"lisi"}  ->{"name":"lisi"}  servlet -> json  ->{"name":"lisi"}
    //@RequestBody  声明前端传递的是json格式的数据
    @RequestMapping(value = "p6",method = RequestMethod.POST)
    public  String  param6(@RequestBody User user){

        System.out.println(user);

        return "index";
    }

}
